package org.leetcode.middle.leetcode107;

import org.leetcode.TreeNode;

import java.util.*;

public class Solution
{
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        checkFun(root,res);
        return res;
    }

    public void checkFun(TreeNode node, List<List<Integer>> res)
    {
        if (node==null)
        {
            return;
        }

        Queue<TreeNode> queue = new LinkedList<>();

        queue.offer(node);

        while (!queue.isEmpty())
        {
            List<Integer> itemList = new ArrayList<>();

            int length = queue.size();

            while (length>0)
            {
                TreeNode tempNode = queue.poll();

                itemList.add(tempNode.val);

                if (tempNode.left!=null) queue.add(tempNode.left);

                if (tempNode.right!=null) queue.add(tempNode.right);

                length--;
            }

            res.add(itemList);
        }

        Collections.reverse(res);
    }

    public static void main(String[] args) {
        List<List<Integer>> testList = new ArrayList<>();

        List<Integer> listOne = new ArrayList<>();

        listOne.add(1);
        listOne.add(2);
        listOne.add(3);

        testList.add(listOne);

        List<Integer> listTwo = new ArrayList<>();

        listTwo.add(4);
        listTwo.add(5);
        listTwo.add(6);

        testList.add(listTwo);

        Collections.reverse(testList);

        System.out.println(testList);
    }

}
